package com.wys.spring;

import com.wys.spring.log.RequestLog;
import com.wys.utils.JsonUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.IOException;

public class RestTemplateClientRequestInterceptor implements ClientHttpRequestInterceptor {


    private final static Logger logger = LoggerFactory.getLogger(RestTemplateClientRequestInterceptor.class);

    private final SpringCommonProperties springCommonProperties;

    public RestTemplateClientRequestInterceptor(SpringCommonProperties springCommonProperties) {
        this.springCommonProperties = springCommonProperties;
    }

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        if (ObjectUtils.isNotEmpty(springCommonProperties.getLogging())&&springCommonProperties.getLogging().getRequestEnable()) {
            RequestLog requestLog = RequestLog.createRequestLog(request, IOUtils.toString(body, "UTF-8"), null);
            logger.warn("拦截RestTemplate请求:{}", JsonUtils.object2Json(requestLog));
        }
        return execution.execute(request, body);
    }
}
